﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Http;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Extentions;
using TrainingReminderSystem.Model;
using TrainingReminderSystem.Dal;
using System.Threading.Tasks;

namespace TrainingReminderSystem.Bll
{
    /// <summary>
    /// 扫码记录 逻辑层
    /// </summary>
    public partial class SysQrCodeBll : PcLoginedBll
    {
        #region 添加和编辑的时候 验证数据和设置默认值

        /// <summary>
        /// 添加和编辑的时候 验证数据和设置默认值
        /// </summary>
        /// <param name="model"></param>
        /// <param name="isAdd">添加还是编辑,可以不管此参数</param>/// <param name="db"></param>
        /// <returns>是否通过,true表示验证通过,false代表验证没有通过</returns>
        public AjaxResult<dynamic> Validate(SysQrCode model, bool isAdd, DbEntities db)
        {
            var r = new AjaxResult<dynamic>();
            if (model == null)
            {
                r.Message = LanguageHelper.NoSubmitData;
                return r;
            }
            model.ExTrimProperty();

            if (string.IsNullOrEmpty(model.OpenID))
            {
                r.Message = LanguageHelper.RequireString1<SysQrCode>(nameof(SysQrCode.OpenID));
                return r;
            }
            if (string.IsNullOrEmpty(model.EventKey))
            {
                r.Message = LanguageHelper.RequireString1<SysQrCode>(nameof(SysQrCode.EventKey));
                return r;
            }

            if (isAdd)
            {
                model.CreateDate = DateTime.Now;
            }

            r = ValidatePartial(model, isAdd, r, db);
            if (r.Success == false) return r;
            r.Success = true;
            return r;
        }

        #endregion

        #region 分页方法

        /// <summary>
        /// 查询条件,能替换掉一些属性查询为自定义查询
        /// </summary>
        /// <param name="where"></param>
        /// <param name="key"></param>
        /// <param name="val"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        private Expression<Func<SysQrCode, bool>> InitSearchDelegete(Expression<Func<SysQrCode, bool>> where, string key, string val, DbEntities db)
        {
            var r = InitSearchDelegetePartial(where, key, val, db);
            if (r != null) return r;
            return null;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="form"></param>
        /// <param name="sortField"></param>
        /// <param name="asc"></param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> GetListByPage(int index, int size, IFormCollection form = null, string sortField = "", bool asc = false)
        {
            using (var db = Db)
            {
                Expression<Func<SysQrCode, bool>> where = InitSearch<SysQrCode, DbEntities>(form, InitSearchDelegete, db); //拼接查询条件方法
                IQueryable<SysQrCode> query = OrderByPartial(db.SysQrCode, sortField, asc, db);
                int counts;
                var tempIDList = query.ExGetListByPage(index, size, out counts, where).Select(m => m.ID);
                var r = new AjaxResult<dynamic>();
                r.Total = counts;
                IQueryable<SysQrCode> list = query.Where(m => tempIDList.Contains(m.ID));
                var tempList = list.Select(m => new
                {
                    ID = m.ID,
                    SysShareRecordID = m.SysShareRecordID,
                    SysShareRecord = new
                    {
                        SysShareRecordID = m.SysShareRecord.SysShareRecordID,
                        EnumShareType = m.SysShareRecord.EnumShareType,
                        m.SysShareRecord.CreateDate,
                        m.SysShareRecord.CompleteDate,
                        m.SysShareRecord.IsComplete,
                        m.SysShareRecord.SysCustomerID
                    },
                    OpenID = m.OpenID,
                    EventKey = m.EventKey,
                    IsComplete = m.IsComplete,
                    CompleteDate = m.CompleteDate,
                    SuccessObj = m.SuccessObj,
                    CreateDate = m.CreateDate,
                    Remark = m.Remark
                });
                var resultList = await tempList.ToListAsync();
                //return GetListByPagePartial(resultList, r, db);

                r.Success = true;
                r.Result = resultList;
                return r;
            }
        }

        #endregion

        #region 得到单对象,返回值有可能为null

        /// <summary>
        /// 得到单对象,返回值有可能为null
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<AjaxResult<SysQrCode>> GetModel(int id)
        {
            using (var db = Db)
            {
                return await GetModel(id, db);
            }
        }

        internal async Task<AjaxResult<SysQrCode>> GetModel(int id, DbEntities db)
        {
            string include = GetModelIncludePartial();
            IQueryable<SysQrCode> query = !string.IsNullOrWhiteSpace(include) ? db.SysQrCode.Include(include) : db.SysQrCode;
            var temp = query.Where(m => m.ID == id);
            var dbModel = await temp.FirstOrDefaultAsync();
            return GetModelReturnPartial(dbModel, db);
        }

        #endregion

        #region 保存数据

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model">保存的对象,成功之后model对象的model对象的主键能得到对象</param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> Save(SysQrCode model)
        {
            using (var db = Db)
            {
                return await Save(model, db);
            }
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model">保存的对象,成功之后model对象的model对象的主键能得到对象</param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> Save(SysQrCode model, DbEntities db)
        {
            if (model.ID <= 0)
            {
                return await Add(model, db);
            }
            return await Update(model, db);
        }

        #endregion

        #region 添加数据

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> Add(SysQrCode model)
        {
            using (var db = Db)
            {
                return await Add(model, db);
            }
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> Add(SysQrCode model, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tempAr = Validate(model, true, db);
            if (tempAr.Success == false)
            {
                r.Message = tempAr.Message;
                r.Result = tempAr.Result;
                r.Total = tempAr.Total;
                return r;
            }
            var tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = await db.Database.BeginTransactionAsync();
            try
            {
                db.SysQrCode.Add(model);
                string error = AddLog(db, model, EnumLogType.新建);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                await db.SaveChangesAsync();
                r = AddUpdateSuccessPartial(model, true, r, db);
                if (r.Success == false)
                {
                    return r;
                }
                await db.SaveChangesAsync();
                if (hasTran == false)
                {
                    await tran.CommitAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
                r.Success = true;
                r.Message = LanguageHelper.Success;
                r.Result = model;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = string.Format(LanguageHelper.Fail1, ex.ExMessageWithInner());
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null)
                {
                    await tran.RollbackAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
            }
        }

        #endregion

        #region 编辑Old

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> Update(SysQrCode model)
        {
            using (var db = Db)
            {
                return await Update(model, db);
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> Update(SysQrCode model, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tempAr = Validate(model, false, db);
            if (tempAr.Success == false)
            {
                r.Message = tempAr.Message;
                r.Result = tempAr.Result;
                r.Total = tempAr.Total;
                return r;
            }
            var tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = await db.Database.BeginTransactionAsync();
            try
            {
                var dbModel = await db.SysQrCode.FirstOrDefaultAsync(m => m.ID == model.ID);
                if (dbModel == null)
                {
                    r.Message = LanguageHelper.NoData;
                    return r;
                }

                dbModel.SysShareRecordID = model.SysShareRecordID;
                dbModel.OpenID = model.OpenID;
                dbModel.EventKey = model.EventKey;
                dbModel.IsComplete = model.IsComplete;
                dbModel.CompleteDate = model.CompleteDate;
                dbModel.SuccessObj = model.SuccessObj;
                dbModel.Remark = model.Remark;

                string error = AddLog(db, model, EnumLogType.编辑);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                await db.SaveChangesAsync();
                r = AddUpdateSuccessPartial(model, false, r, db, dbModel);
                if (r.Success == false)
                {
                    return r;
                }
                await db.SaveChangesAsync();
                if (hasTran == false)
                {
                    await tran.CommitAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
                r.Success = true;
                r.Message = LanguageHelper.Success;
                r.Result = dbModel;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = string.Format(LanguageHelper.Fail1, ex.ExMessageWithInner());
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null)
                {
                    await tran.RollbackAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
            }
        }

        #endregion

        //#region 编辑New

        ///// <summary>
        ///// 编辑
        ///// </summary>
        ///// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        ///// <returns></returns>
        //public async Task<AjaxResult<dynamic>> Modify(SysQrCode model)
        //{
        //    using (var db = Db)
        //    {
        //        return await Modify(model, db);
        //    }
        //}

        ///// <summary>
        ///// 编辑
        ///// </summary>
        ///// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        ///// <param name="db"></param>
        ///// <returns></returns>
        //internal async Task<AjaxResult<dynamic>> Modify(SysQrCode model, DbEntities db)
        //{
        //    var r = new AjaxResult<dynamic>() { Success = false };
        //    if (db == null) db = Db;
        //    var tempAr = Validate(model, false, db);
        //    if (tempAr.Success == false)
        //    {
        //        r.Message = tempAr.Message;
        //        r.Result = tempAr.Result;
        //        r.Total = tempAr.Total;
        //        return r;
        //    }
        //    var tran = db.Database.CurrentTransaction;
        //    bool hasTran = tran != null;
        //    if (hasTran == false) tran = await db.Database.BeginTransactionAsync();
        //    try
        //    {
        //        await ModifyBaseAsync(model, db, typeof(SysQrCode));

        //        string error = AddLog(db, model, EnumLogType.编辑);
        //        if (!string.IsNullOrEmpty(error))
        //        {
        //            return AjaxResult<dynamic>.ErrorResult(error);
        //        }
        //        await db.SaveChangesAsync();
        //        r = AddUpdateSuccessPartial(model, false, r, db);
        //        if (r.Success == false)
        //        {
        //            return r;
        //        }
        //        await db.SaveChangesAsync();
        //        if (hasTran == false)
        //        {
        //            await tran.CommitAsync();
        //            await tran.DisposeAsync();
        //            tran = null;
        //        }
        //        r.Success = true;
        //        r.Message = LanguageHelper.Success;
        //        r.Result = model;
        //        return r;
        //    }
        //    catch (Exception ex)
        //    {
        //        ex.ExLogError(GetCurrentOther());
        //        r.Total = (int)EnumTotal.异常;
        //        r.Success = false;
        //        r.Message = string.Format(LanguageHelper.Fail1, ex.ExMessageWithInner());
        //        return r;
        //    }
        //    finally
        //    {
        //        if (hasTran == false && tran != null)
        //        {
        //            await tran.RollbackAsync();
        //            await tran.DisposeAsync();
        //            tran = null;
        //        }
        //    }
        //}

        //#endregion

        #region 删除

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> Del(int id)
        {
            using (var db = Db)
            {
                return await Del(id, db);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> Del(int id, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = await db.Database.BeginTransactionAsync();
            try
            {
                var dbModel = await db.SysQrCode.FirstOrDefaultAsync(m => m.ID == id);
                if (dbModel == null)
                {
                    r.Message = LanguageHelper.NoData;
                    return r;
                }

                r = DelValidatePartial(dbModel, r, db);
                if (r.Success == false)
                {
                    return r;
                }
                db.SysQrCode.Remove(dbModel);
                string error = AddLog(db, dbModel, EnumLogType.删除);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                await db.SaveChangesAsync();
                r = DelSuccessPartial(dbModel, r, db);
                if (r.Success == false)
                {
                    return r;
                }
                await db.SaveChangesAsync();
                if (hasTran == false)
                {
                    await tran.CommitAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
                r.Success = true;
                r.Message = LanguageHelper.Success;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = string.Format(LanguageHelper.Fail1, ex.ExMessageWithInner());
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null)
                {
                    await tran.RollbackAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
            }
        }

        #endregion

        #region 下拉选择

        /// <summary>
        /// 下拉选择
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> GetListSelect(IFormCollection form = null)
        {
            using (var db = Db)
            {
                Expression<Func<SysQrCode, bool>> where = InitSearch<SysQrCode, DbEntities>(form, InitSearchDelegete, db); //拼接查询条件方法
                var selectID = form["selectIDName"].ExTrim();
                var obj = db.SysQrCode.AsNoTracking();
                bool hasSelectID = false;
                if (!string.IsNullOrEmpty(selectID))
                {
                    if (selectID.IndexOf(',') != -1)
                    {
                        var selectIDList = selectID.ExToSplitList(',', false);
                        if (selectIDList.Count > 0)
                        {
                            hasSelectID = true;
                            obj = obj.OrderByDescending(m => selectIDList.Contains(m.ID)).ThenByDescending(m => m.ID);
                        }
                    }
                    else
                    {
                        var selectIDInt = selectID.ExToInt32();
                        if (selectIDInt > 0)
                        {
                            hasSelectID = true;
                            obj = obj.OrderByDescending(m => selectIDInt == m.ID).ThenByDescending(m => m.ID);
                        }
                    }
                    if (hasSelectID == false)
                    {
                        obj = obj.OrderByDescending(m => m.ID);
                        where = where.ExAnd(m => m.OpenID.Contains(selectID));
                    }
                }
                if (hasSelectID == false)
                {
                    obj = obj.OrderByDescending(m => m.ID);
                    //where = where.ExAnd(m => m.EnumStatus == EnumStatus.启用);
                }
                var result = new AjaxResult<dynamic>() { Success = true };
                IQueryable<SysQrCode> list = obj.Where(where).Take(DefaultSize);
                var tempList = list.Select(m => new SysQrCode()
                {

                });
                result.Result = await tempList.ToListAsync();
                return result;
            }
        }

        #endregion

        //#region 导入
        //#endregion
    }
}
